package com.dlry.serviceImpl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import com.dlry.db.UserRepository;
import com.dlry.entity.DlLoginuser;
import com.dlry.sexurity.model.DlUser;

@Service

public class UserDetailsServiceImpl implements UserDetailsService {
	@Autowired
	private final UserRepository userRepository;

	public UserDetailsServiceImpl(UserRepository userRepository) {
		this.userRepository = userRepository;
	}

	public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
		DlLoginuser loginuser = userRepository.findByName(userName);
		if (loginuser == null) {
			throw new UsernameNotFoundException(userName + ": 未找到此用户");
		}
		List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
		String rolestr = loginuser.getRoles();
		String[] roles = rolestr.split(",");
		for (String role : roles) {
			authorities.add(new SimpleGrantedAuthority(role));
		}
		DlUser user = new DlUser(loginuser.getName(), loginuser.getPassword(), loginuser.getEnabled(), true, true, true,
				authorities);
		user.setRealName(loginuser.getRealName());
		return user;
	}

}
